<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('optimize_image'))
{
	function optimize_image($file, $quality = 90)
	{
		// Check that the file isn't already compressed
		if (preg_match('/^\.compressed\./', pathinfo($file, PATHINFO_FILENAME)))
		{
			return $file;
		}

		// What's the new filename?
		$new_file = pathinfo($asset['file'], PATHINFO_DIRNAME).'/'.pathinfo($file,	PATHINFO_BASENAME).
			'.optimized.'.pathinfo($file, PATHINFO_EXTENSION);

		// What's the current image string
		$image_string = imagecreatefromstring(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/'.$file));

		// Go through the different image files and optimize
		switch (pathinfo(strtolower($file), PATHINFO_EXTENSION))
		{
			case 'jpg':
			case 'jpeg':
				imagejpeg($image_string, $_SERVER['DOCUMENT_ROOT'].'/'.$new_file, $quality);
				break;
			case 'png':
				imagepng($image_string, $_SERVER['DOCUMENT_ROOT'].'/'.$new_file, $quality);
				break;
			case 'gif':
				$im = new Imagick($image_string);
				$im->optimizeImageLayers();
				$im->writeimage($_SERVER['DOCUMENT_ROOT'].'/'.$new_file);
				break;

		}
		return $new_file;
	}
}